package admin

import (
	"MBGAdmin/util"
	"github.com/astaxie/beego"
	"golang.org/x/crypto/bcrypt"
	"os"
	"path/filepath"
	"runtime"
)

// 首页控制器
type IndexController struct {
	AuthController
}

// 后台登录首页
func (c *IndexController) Get() {
	// 从session中获取当前管理员的权限菜单
	c.Data["menus"] = c.GetSession("menus")
	c.Display("admin/index/index.html")
}

// 桌面首页
func (c *IndexController) Desktop() {
	c.Data["host"] = c.Ctx.Input.Host()
	c.Data["system"] = runtime.GOOS + "/" + runtime.GOARCH
	c.Data["runPath"], _ = filepath.Abs(filepath.Dir(os.Args[0]))
	c.Data["goVersion"] = runtime.Version()
	c.Data["goPath"] = runtime.GOROOT()
	c.Data["mysqlVersion"] = util.GetMysqlVersion().(string)
	c.Data["beegoVersion"] = beego.VERSION

	c.Display("admin/index/desktop.html")
}

// 缓存首页
func (c *IndexController) CacheView() {
	c.Display("admin/index/cache.html")
}

// 缓存清理
func (c *IndexController) CacheClear() {
	err := os.RemoveAll("session")
	if err != nil {
		c.BaseResponse(0, "清理失败:"+err.Error())
	}
	c.BaseResponse(0, "清理成功")
}

// 修改密码页面
func (c *IndexController) PasswordView() {
	c.Display("admin/index/password.html")
}

// 修改密码
func (c *IndexController) UpdatePassword() {
	oldPassword := c.GetString("oldPassword")
	newPassword := c.GetString("newPassword")
	newPasswordConfirmation := c.GetString("newPasswordConfirmation")
	// 验证重复密码是否一样
	if newPassword != newPasswordConfirmation {
		c.BaseResponse(1, "重复新密码不正确")
		return
	}
	// 验证密码是否匹配
	err := bcrypt.CompareHashAndPassword([]byte(util.PhpToGoLang(c.Admin.Password)), []byte(oldPassword))
	if err != nil {
		c.BaseResponse(1, "密码校验不通过")
		return
	}
	passwordHash, _ := bcrypt.GenerateFromPassword([]byte(newPassword), bcrypt.DefaultCost)
	c.Admin.Password = util.GoLangToPhp(string(passwordHash))
	err = c.Admin.UpdateAdminsById()
	if err != nil {
		c.BaseResponse(1, "密码修改失败")
		return
	}
	c.BaseResponse(0, "密码修改成功")
}
